package cn.codeforfun.common;

import cn.codeforfun.consts.WeixinConst;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2017/2/14 0014.
 */
@Component
public class WechatService {
    @Autowired
    private WeixinConst weixinConst;
    private WxMpService wxService;
    private static Object lock = new Object();

    public void init() {
        WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
        config.setAppId(weixinConst.getAppid()); // 设置微信公众号的appid
        config.setSecret(weixinConst.getAppsecret()); // 设置微信公众号的app corpSecret
//        config.setToken("..."); // 设置微信公众号的token
//        config.setAesKey("..."); // 设置微信公众号的EncodingAESKey

        this.wxService = new WxMpServiceImpl();
        this.wxService.setWxMpConfigStorage(config);
    }

    public WxMpService getService() {
        synchronized (lock) {
            if (this.wxService == null) {
                this.init();
            }
        }
        return this.wxService;
    }

}
